/*
 * @Descripttion:
 * @LastEditors: chen.long
 * @LastEditTime: 2024-02-24 14:00:54
 */

import { appRouteParse } from '../utils';
import {
  anchorElementGenerator,
  getAnchorElementQueryMap,
  getSyncUrl
} from '../utils/element';

/**
 * @Author: chen.long
 * @Descripttion: 同步子应用路由到主应用路由
 * @Param:
 * @param {Window} iframeWindow
 */
export function syncUrlToWindow(iframeWindow: Window): void {
  const { id } = iframeWindow.__YBMICRO;
  let winUrlElement = anchorElementGenerator(window.location.href);
  const queryMap = getAnchorElementQueryMap(winUrlElement);
  const curUrl =
    iframeWindow.location.pathname +
    iframeWindow.location.search +
    iframeWindow.location.hash;
  // 同步
  queryMap[id] = window.encodeURIComponent(curUrl);
  const newQuery =
    '?' +
    Object.keys(queryMap)
      .map(key => key + '=' + queryMap[key])
      .join('&');
  winUrlElement.search = newQuery;
  if (winUrlElement.href !== window.location.href) {
    window.history.replaceState(null, '', winUrlElement.href);
  }
  winUrlElement = null;
}

/**
 * @Author: chen.long
 * @Descripttion: 同步主应用路由到子应用
 * @Param:
 * @param {Window} iframeWindow
 */
export function syncUrlToIframe(iframeWindow: Window): void {
  // 获取当前路由路径
  const { pathname, search, hash } = iframeWindow.location;
  const { id, url, execFlag, inject } = iframeWindow.__YBMICRO;

  // 只在浏览器刷新或者第一次渲染时同步
  const idUrl = !execFlag ? getSyncUrl(id) : url;
  // 排除href跳转情况
  const syncUrl = (/^http/.test(idUrl) ? null : idUrl) || url;
  const { appRoutePath } = appRouteParse(syncUrl);

  const preAppRoutePath = pathname + search + hash;
  if (preAppRoutePath !== appRoutePath) {
    iframeWindow.history.replaceState(
      null,
      '',
      inject.mainHostPath + appRoutePath
    );
  }
}

/**
 * @Author: chen.long
 * @Descripttion: 推送指定url到主应用路由
 * @Param:
 * @param {string} id 子应用id
 * @param {string} url 子应用url
 */
export function pushUrlToWindow(id: string, url: string): void {
  let winUrlElement = anchorElementGenerator(window.location.href);
  const queryMap = getAnchorElementQueryMap(winUrlElement);
  queryMap[id] = window.encodeURIComponent(url);
  const newQuery =
    '?' +
    Object.keys(queryMap)
      .map(key => key + '=' + queryMap[key])
      .join('&');
  winUrlElement.search = newQuery;
  window.history.pushState(null, '', winUrlElement.href);
  winUrlElement = null;
}
